package logic

import (
	"context"
	"database/sql"
	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"
	"fmt"
	"strconv"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
)



type ServeyClasifyUpdateLogic struct{
	logx.Logger
	ctx context.Context
	rds *redis.Redis
	svcCtx *svc.ServiceContext
	model model.ServeyClassifyModel
}

func NewServeyClassifyUpdateLogic(ctx context.Context,svcCtx *svc.ServiceContext)*ServeyClasifyUpdateLogic{
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: svcCtx.Config.Redis.Host,
		Pass: svcCtx.Config.Redis.Pass,
		Type: svcCtx.Config.Redis.Type,
	})
	if err != nil {
		logx.Errorf("redis init error: %v", err)
	}

	return &ServeyClasifyUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx: ctx,
		svcCtx: svcCtx,
		rds: rds,
		model: model.NewServeyClassifyModel(svcCtx.Orm,svcCtx.GormDB),
	}
}

func (l *ServeyClasifyUpdateLogic)Update(req *types.ServeyClassifyUpdateRequest)(resp *types.ServeyClassifyCreateResponse,err error){

	payload,ok := l.ctx.Value("payload").(string)
	if !ok {
		return nil,errorx.NewBizError(500,"用户ID获取失败")
	}

	userId,err := strconv.ParseInt(payload,10,64)
	if err != nil{
		return nil,errorx.NewBizError(500,"字符串格式转换错误")
	}

	// step1 check request params
	sc,err := l.model.FindOne(l.ctx,req.Id)
	if sc == nil || err != nil {
		return nil,errorx.NewBizError(500,"数据错误")
	}
	if sc.CreatorId != userId {
		return nil,errorx.NewBizError(500,"违规操作")
	}
	
	// 删除redis中的数据
	l.rds.DelCtx(l.ctx,ServeyClassifyDetailPrefix + strconv.FormatInt(req.Id,10))

	// step2 update data
	if len(strings.TrimSpace(req.ClfName)) == 0{
		return nil,errorx.NewBizError(500,"问卷分类名不能为空")
	} 
	flag := 0
	if req.ClfName != sc.ClfName {
		sc.ClfName = req.ClfName
		flag = 1
	}
	if len(strings.TrimSpace(req.ClfDesc)) != 0 && req.ClfDesc != sc.ClfDesc.String {
		sc.ClfDesc = sql.NullString{String: req.ClfDesc,Valid: true,}
		flag = 1
	}
	if flag == 1 {
		// judge data isn't exist database
		scone,err := l.model.FindOneByNameAndCreatorID(l.ctx,req.ClfName,userId)
		if scone != nil ||(err != nil && err != model.ErrNotFound) {
			return nil,errorx.NewBizError(500,"数据库异常，请重试~~")
		}
		err = l.model.Update(l.ctx,sc)
		if err != nil {
			fmt.Println(err)
			return nil,errorx.NewBizError(200,"错误的码")
		}
		return &types.ServeyClassifyCreateResponse{
			CommonResponse: types.CommonResponse{
				Code: 200,
				Msg: "update success",
			},
		},nil
	}else{
		return &types.ServeyClassifyCreateResponse{
			CommonResponse: types.CommonResponse{
				Code: 500,
				Msg: "nothing changed",
			},
		},nil
	}
}